package com.zmn.oms.zmn.business.impl.work;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerDetailInfoDRO;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerListRemoteService;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductBusinessLineForeignListRemoteService;
import com.zmn.brs.common.enums.EventEnum;
import com.zmn.brs.common.enums.RecordFieldEnum;
import com.zmn.brs.starter.annotation.RecordField;
import com.zmn.brs.starter.annotation.StaffOperateRecord;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.Option;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.excel.ExportExcelBuilder;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.mcc.dubbo.interfaces.role.RoleListRemoteService;
import com.zmn.mcc.dubbo.interfaces.staff.StaffListRemoteService;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.enums.EncryptFieldTypeEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.model.entity.channelprepay.OrderChannelPrepay;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.entity.xno.OrderXnoBind;
import com.zmn.base.oms.common.model.es.orderwork.*;
import com.zmn.oms.model.vo.work.ZsOrderWorkServiceItemExportVO;
import com.zmn.oms.services.interfaces.channelprepay.OrderChannelPrepayService;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import com.zmn.oms.services.interfaces.xno.OrderXnoService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryExportBService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.tapi.common.export.model.dio.AddExportTaskDIO;
import com.zmn.tapi.common.export.model.dio.ExportHttpDIO;
import com.zmn.tapi.common.export.model.dio.SheetDIO;
import com.zmn.tapi.dubbo.interfaces.export.ExportModifyRemoteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：工单导出
 *
 * @author lujia
 * @date 2019/03/21 15:17
 */
@Service
public class ZsOrderWorkQueryExportBServiceImpl implements ZsOrderWorkQueryExportBService {

    // 导出文件名称
    public static final String ORDER_FILE_NAME = "工单管理";

    // 导出类型
    public static final String EXPORT_TYPE = "工单列表";

    // 导出文件类型
    public static final String EXPORT_FILE_TYPE = ".xlsx";

    // sheet1名称
    public static final String ORDER_SHEET_ONE_NAME = "工单信息";

    // sheet2名称
    public static final String ORDER_SHEET_TWO_NAME = "服务项目";

    // tapi导出服务地址
    @Value("${zmn.tapi.export.url:http://test2-tapi.xiujiadian.com/api/export/exportMultipleSheetInfo}")
    private String ZMN_TAPI_EXPORT_URL;

    private static LinkedHashMap<String, String> sheetOneMap = Maps.newLinkedHashMap();

    static {
        sheetOneMap.put("platCallback", "下单平台");
        sheetOneMap.put("receiveTime", "下单时间");
        sheetOneMap.put("firstDutyTime", "首次预约时间");
        sheetOneMap.put("firstDutyOptTime", "首次操作预约时间点");
        sheetOneMap.put("lastDutyTime", "末次预约时间");
        sheetOneMap.put("lastDutyOptTime", "末次操作预约时间点");
        sheetOneMap.put("suspendTime", "挂起时间");
        sheetOneMap.put("distributeTime", "派单时间");
        sheetOneMap.put("visitTime", "上门时间");
        sheetOneMap.put("cancelTimeCallback", "取消时间");
        sheetOneMap.put("serviceCompleteTime", "服务完成时间");
        sheetOneMap.put("completeTime", "完成时间");
        sheetOneMap.put("accountTime", "算账时间");
        sheetOneMap.put("channelStatementCanTime", "可结算时间");

        sheetOneMap.put("id", "工单号");
        sheetOneMap.put("extOuterId", "渠道父订单号");
        sheetOneMap.put("extOuterSubId", "渠道子订单号");
        sheetOneMap.put("companyName", "子公司");
        sheetOneMap.put("provinceName", "省份");
        sheetOneMap.put("naturalCityName", "城市");
        sheetOneMap.put("countyName", "区域");
        sheetOneMap.put("addressCallback", "地址");

        sheetOneMap.put("userNameCallback", "用户姓名");
        sheetOneMap.put("userPhoneNameCallback", "用户电话");
        sheetOneMap.put("genderCallback", "性别");

        sheetOneMap.put("factoryCallback", "厂商");
        sheetOneMap.put("factoryProductCallback", "厂商产品");

        sheetOneMap.put("bizTypeCallback", "业务类型");
        sheetOneMap.put("bizLineCallback", "业务线");
        sheetOneMap.put("servProductGroupName", "产品组");
        sheetOneMap.put("servCategName", "服务分类");
        sheetOneMap.put("showProductCallback", "前台服务产品");
        sheetOneMap.put("productCallback", "后台服务产品");
        sheetOneMap.put("productUnitCallback", "产品单位");
        sheetOneMap.put("productBrandCallback", "产品品牌");
        sheetOneMap.put("productNumCallback", "数量");
        sheetOneMap.put("typeName", "返修新单");
        sheetOneMap.put("standardPriceCallback", "标准收费单");
        sheetOneMap.put("finalPriceRateCallback", "是否一口价");

        sheetOneMap.put("originalIdCallback", "源单号");
        sheetOneMap.put("faultContent", "故障内容");
        sheetOneMap.put("remark", "下单备注");
        sheetOneMap.put("platWorkCallback", "服务平台");
        sheetOneMap.put("serviceProviderCallback", "服务商");

        sheetOneMap.put("masterNameCallback", "主工程师");
        sheetOneMap.put("cancelLiableNameCallback", "责任工程师");
        sheetOneMap.put("slaveMasterNameCallback", "多工程师");
        sheetOneMap.put("masterSupervisorNameCallback", "工程师主管");
        sheetOneMap.put("reworkMasterNameCallback", "源工程师");
        sheetOneMap.put("statusName", "状态");
        sheetOneMap.put("resultStatusName", "结果");
        sheetOneMap.put("originalAmountCallback", "订单金额");
        sheetOneMap.put("discountAmountCallback", "优惠");
        sheetOneMap.put("totalAmountCallback", "订单收入");
        sheetOneMap.put("channelPrepayAmountCallback", "渠道预收");
        sheetOneMap.put("depositAmountCallback", "定金");
        sheetOneMap.put("masterAmountCallback", "工程师收款金额");
        sheetOneMap.put("refundAmountCallback", "退款金额");
        sheetOneMap.put("channelAmountCallback", "渠道费");

        sheetOneMap.put("payStatusName", "支付状态");
        sheetOneMap.put("suspendContent", "挂起原因");
        sheetOneMap.put("failContent", "取消缘由");
        sheetOneMap.put("discardContent", "取消备注");
        sheetOneMap.put("outerId", "渠道单号");
        sheetOneMap.put("receiveEntranceNameCallback", "入口");
        sheetOneMap.put("receiverTypeCallback", "录单人类型");
        sheetOneMap.put("receiverId", "录单人ID");
        sheetOneMap.put("receiverNameCallBack", "录单员");
        sheetOneMap.put("commentScore", "评星");
        sheetOneMap.put("replyContent", "回访评分内容");
        sheetOneMap.put("orderNonstandardTitleOneCallback", "信息名称1");
        sheetOneMap.put("orderNonstandardContentOneCallback", "信息内容1");
        sheetOneMap.put("orderNonstandardTitleTwoCallback", "信息名称2");
        sheetOneMap.put("orderNonstandardContentTwoCallback", "信息内容2");
        sheetOneMap.put("orderNonstandardTitleThreeCallback", "信息名称3");
        sheetOneMap.put("orderNonstandardContentThreeCallback", "信息内容3");
        sheetOneMap.put("modifyTypeCallback", "改约改派");
        sheetOneMap.put("preConstructionPictureCallback", "施工前照片");
        sheetOneMap.put("afterCompletionPictureCallback", "完工后照片");
        sheetOneMap.put("masterImageCallback", "形象照");
        sheetOneMap.put("appliqueImageCallback", "贴花照片");
        sheetOneMap.put("gridName", "网格");
        sheetOneMap.put("tempXno", "临时小号");

    }

    private static LinkedHashMap<String, String> sheetTwoMap = Maps.newLinkedHashMap();

    static {
        sheetTwoMap.put("receiveTime", "下单时间");
        sheetTwoMap.put("completeTime", "完成时间");
        sheetTwoMap.put("id", "工单号");
        sheetTwoMap.put("companyName", "子公司");
        sheetTwoMap.put("naturalCityName", "城市");
        sheetTwoMap.put("masterNameCallback", "主工程师");
        sheetTwoMap.put("statusName", "状态");
        sheetTwoMap.put("resultStatusName", "结果");
        sheetTwoMap.put("servCategName", "服务分类");
        sheetTwoMap.put("originalAmountCallback", "订单金额");
        sheetTwoMap.put("discountAmountCallback", "优惠");
        sheetTwoMap.put("totalAmountCallback", "订单收入");
        sheetTwoMap.put("productName", "服务产品");
        sheetTwoMap.put("productNum", "产品数量");
        sheetTwoMap.put("serviceItemName", "服务项目");
        sheetTwoMap.put("serviceItemNum", "服务项目数量");
        sheetTwoMap.put("serviceItemPriceCallback", "服务项单价");
    }

    // 标签1的大小
    private static int sheetOneSize = 100;

    // 标签2的大小
    private static int sheetTwoSize = 17;

    private static List<String> sheetOneFirstRowList = Lists.newArrayListWithCapacity(sheetOneSize);

    static {
        sheetOneFirstRowList.add("下单平台");
        sheetOneFirstRowList.add("下单时间");
        sheetOneFirstRowList.add("首次预约时间");
        sheetOneFirstRowList.add("首次操作预约时间点");
        sheetOneFirstRowList.add("末次预约时间");
        sheetOneFirstRowList.add("末次操作预约时间点");
        sheetOneFirstRowList.add("挂起时间");
        sheetOneFirstRowList.add("派单时间");
        sheetOneFirstRowList.add("上门时间");
        sheetOneFirstRowList.add("取消时间");
        sheetOneFirstRowList.add("服务完成时间");
        sheetOneFirstRowList.add("完成时间");
        sheetOneFirstRowList.add("算账时间");
        sheetOneFirstRowList.add("可结算时间");

        sheetOneFirstRowList.add("工单号");
        sheetOneFirstRowList.add("渠道父订单号");
        sheetOneFirstRowList.add("渠道子订单号");
        sheetOneFirstRowList.add("子公司");
        sheetOneFirstRowList.add("省份");
        sheetOneFirstRowList.add("城市");
        sheetOneFirstRowList.add("区域");
        sheetOneFirstRowList.add("地址");

        sheetOneFirstRowList.add("用户姓名");
        sheetOneFirstRowList.add("用户电话");
        sheetOneFirstRowList.add("性别");

        sheetOneFirstRowList.add("厂商");
        sheetOneFirstRowList.add("厂商产品");

        sheetOneFirstRowList.add("业务类型");
        sheetOneFirstRowList.add("业务线");
        sheetOneFirstRowList.add("产品组");
        sheetOneFirstRowList.add("服务分类");
        sheetOneFirstRowList.add("前台服务产品");
        sheetOneFirstRowList.add("后台服务产品");
        sheetOneFirstRowList.add("产品单位");
        sheetOneFirstRowList.add("产品品牌");
        sheetOneFirstRowList.add("数量");
        sheetOneFirstRowList.add("工单类型");
        sheetOneFirstRowList.add("标准收费单");
        sheetOneFirstRowList.add("是否一口价");

        sheetOneFirstRowList.add("源单号");
        sheetOneFirstRowList.add("故障内容");
        sheetOneFirstRowList.add("下单备注");
        sheetOneFirstRowList.add("服务平台");
        sheetOneFirstRowList.add("服务商");

        sheetOneFirstRowList.add("主工程师");
        sheetOneFirstRowList.add("责任工程师");
        sheetOneFirstRowList.add("多工程师");
        sheetOneFirstRowList.add("工程师主管");
        sheetOneFirstRowList.add("源工程师");
        sheetOneFirstRowList.add("状态");
        sheetOneFirstRowList.add("结果");
        sheetOneFirstRowList.add("订单金额");
        sheetOneFirstRowList.add("平台代收金额");
        sheetOneFirstRowList.add("优惠");
        sheetOneFirstRowList.add("优惠规则ID");
        sheetOneFirstRowList.add("优惠券批次ID");
        sheetOneFirstRowList.add("订单收入");
        sheetOneFirstRowList.add("渠道预收");
        sheetOneFirstRowList.add("渠道预收明细");
        sheetOneFirstRowList.add("定金");
        sheetOneFirstRowList.add("工程师收款金额");
        sheetOneFirstRowList.add("退款单号");
        sheetOneFirstRowList.add("打款日期");
        sheetOneFirstRowList.add("退款金额");
        sheetOneFirstRowList.add("退款单支付状态");
        sheetOneFirstRowList.add("退款手续费");
        sheetOneFirstRowList.add("退款缘由");
        sheetOneFirstRowList.add("退款方式");
        sheetOneFirstRowList.add("退款路径");
        sheetOneFirstRowList.add("支付宝户名");
        sheetOneFirstRowList.add("支付宝账号");
        sheetOneFirstRowList.add("微信ID");
        sheetOneFirstRowList.add("微信姓名");
        sheetOneFirstRowList.add("银行卡开户行");
        sheetOneFirstRowList.add("银行卡号");
        sheetOneFirstRowList.add("户名");
        sheetOneFirstRowList.add("退款单录单人");
        sheetOneFirstRowList.add("打款人");
        sheetOneFirstRowList.add("打款银行");
        sheetOneFirstRowList.add("退款凭证号");
        sheetOneFirstRowList.add("退款凭证备注");
        sheetOneFirstRowList.add("渠道费");

        sheetOneFirstRowList.add("支付状态");
        sheetOneFirstRowList.add("挂起原因");
        sheetOneFirstRowList.add("取消缘由");
        sheetOneFirstRowList.add("取消备注");
        sheetOneFirstRowList.add("下单渠道");
        sheetOneFirstRowList.add("来源渠道");
        sheetOneFirstRowList.add("渠道单号");
        /*TODO 2022年1月20日15:34:20 新增字段*/
        sheetOneFirstRowList.add("执行子公司");
        sheetOneFirstRowList.add("行政子公司");
        sheetOneFirstRowList.add("执行服务商");
        sheetOneFirstRowList.add("行政服务商");

        sheetOneFirstRowList.add("入口");
        sheetOneFirstRowList.add("录单人类型");
        sheetOneFirstRowList.add("录单人ID");
        sheetOneFirstRowList.add("录单员");
        sheetOneFirstRowList.add("会员等级");
        sheetOneFirstRowList.add("评星");
        sheetOneFirstRowList.add("回访评分内容");
        sheetOneFirstRowList.add("信息名称1");
        sheetOneFirstRowList.add("信息内容1");
        sheetOneFirstRowList.add("信息名称2");
        sheetOneFirstRowList.add("信息内容2");
        sheetOneFirstRowList.add("信息名称3");
        sheetOneFirstRowList.add("信息内容3");
        sheetOneFirstRowList.add("改约改派");
        sheetOneFirstRowList.add("施工前照片");
        sheetOneFirstRowList.add("完工后照片");
        sheetOneFirstRowList.add("形象照");
        sheetOneFirstRowList.add("贴花照片");
        sheetOneFirstRowList.add("网格");
        sheetOneFirstRowList.add("临时小号");
    }

    private static List<String> sheetTwoFirstRowList = Lists.newArrayListWithCapacity(sheetTwoSize);

    static {
        sheetTwoFirstRowList.add("下单时间");
        sheetTwoFirstRowList.add("完成时间");
        sheetTwoFirstRowList.add("工单号");
        sheetTwoFirstRowList.add("子公司");
        sheetTwoFirstRowList.add("城市");
        sheetTwoFirstRowList.add("主工程师");
        sheetTwoFirstRowList.add("状态");
        sheetTwoFirstRowList.add("结果");
        sheetTwoFirstRowList.add("服务分类");
        sheetTwoFirstRowList.add("订单金额");
        sheetTwoFirstRowList.add("优惠");
        sheetTwoFirstRowList.add("订单收入");
        sheetTwoFirstRowList.add("服务产品");
        sheetTwoFirstRowList.add("产品数量");
        sheetTwoFirstRowList.add("服务项目");
        sheetTwoFirstRowList.add("服务项目数量");
        sheetTwoFirstRowList.add("服务项单价");
    }

    private static final String TAG = "啄木鸟-工单导出";
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    OrderEncryptService orderEncryptService;
    @Resource
    ZmnMQSender zmnMQSender;
    @Resource
    OrderXnoService orderXnoService;
    @Autowired
    OrderChannelPrepayService orderChannelPrepayService;

//    @Reference(version = com.zmn.mer.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
//    protected FactoryListRemoteService factoryListRemoteService;
    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    protected EngineerListRemoteService engineerListRemoteService;
    @Reference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    protected StaffListRemoteService staffListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ProductBusinessLineForeignListRemoteService productBusinessLineForeignListRemoteService;
    @Reference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    private RoleListRemoteService roleListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false, timeout = 10000)
    private ChannelListRemoteService channelListRemoteService;
    @org.apache.dubbo.config.annotation.Reference(version = com.zmn.tapi.dubbo.DubboConsts.INTERFACE_VERSION, check = false)
    private ExportModifyRemoteService exportModifyRemoteService;

    @StaffOperateRecord(staffId = "{{#query.staffId}}",
            event = EventEnum.WORK_ORDER_EXPORT,
            mapping = {
                    @RecordField(field = RecordFieldEnum.STAFF_IP, value = "{{#query.ip}}"),
                    @RecordField(field = RecordFieldEnum.PLAT, value = "{{#query.platWork}}")
            })
    @Override
    public ExportExcelBuilder exportListOrderWorkByQuery(OrderWorkQuery query, Boolean supportServiceItem) {

        zsOrderWorkQueryBService.processWorkQuery(query);

        // 区分平台隐藏电话中间四位
        String url;
        Integer platWork = Optional.ofNullable(query.getPlatWork()).orElse(0);
        switch (platWork) {
            case GlobalConsts.PLAT_MARK_ZMN:
                url = "/work/list/export/show/tel.action";
                break;
            case GlobalConsts.PLAT_MARK_YEYX:
                url = "/ys/work/list/export/show/tel.action";
                break;
            case GlobalConsts.PLAT_MARK_SAAS:
                url = "/saas/work/list/export/show/tel.action";
                break;
            case GlobalConsts.PLAT_MARK_CNHB:
                url = "/cnhb/work/list/export/show/tel.action";
                break;
            default:
                url = "/all/work/list/export/show/tel.action";
                break;
        }
        //boolean showTel = StaffAdminService.isPermitted(url);
        boolean showTel = false;

        ExportExcelBuilder excel = new ExportExcelBuilder();

        List<EsOrderWork> orderWorkList = zsOrderWorkQueryBService.exportListOrderWorkByQuery(query);
        // 解密用户地址和电话
        orderEncryptService.batchDecryptEsOrderWork(orderWorkList, EncryptFieldTypeEnum.USER_TELPHONE, EncryptFieldTypeEnum.USER_ADDRESS);
        ExportExcelBuilder.ExcelSheet<EsOrderWork> sheet1 = excel.createExcelSheet("工单信息", orderWorkList, sheetOneMap, true);

        Map<Integer, String> staffMap;
        Map<Integer, String> fcMap;
        Map<Integer, String> masterMap;
        if (orderWorkList.size() > 0) {
            // 录单人处理
            List<Integer> receiverIdList = orderWorkList.stream().
                    filter(orderWork -> orderWork.getReceiverId() != null && (GlobalConsts.OPERATE_USER_TYPE_SYSTEM != orderWork.getReceiverId())). //剔除系统和null
                    map(orderWork -> orderWork.getReceiverId().intValue()).
                    collect(Collectors.toList());
            // 查询员工信息-录单员
            if (receiverIdList.size() > 0) {
                ResponseDTO<List<StaffDRO>> staffList = staffListRemoteService.listStaffByStaffIds(receiverIdList, null);
                staffMap = staffList.getData().stream().collect(Collectors.toMap(StaffDRO::getStaffId, StaffDRO::getRealName, (k1, k2) -> k1));

                // todo fubiao
                logger.info("exportListOrderWorkByQuery#listEngineerDetailByIdSet start [{}]",JSON.toJSONString(receiverIdList));
                ResponseDTO<List<ForeignEngineerDetailInfoDRO>> responseDTO = engineerListRemoteService.listEngineerDetailByIdSet(new HashSet<>(receiverIdList));
                logger.info("exportListOrderWorkByQuery#listEngineerDetailByIdSet end [{}]",JSON.toJSONString(responseDTO));
                if (!responseDTO.isSuccess() || CollectionUtils.isEmpty(responseDTO.getData())) {
                    masterMap = Maps.newHashMap();
                } else {
                    List<ForeignEngineerDetailInfoDRO> items = responseDTO.getData();
                    masterMap = items.stream().collect(Collectors.toMap(ForeignEngineerDetailInfoDRO::getEngineerId, ForeignEngineerDetailInfoDRO::getRealName, (k1, k2) -> k1));
                }

            } else {
                staffMap = Maps.newHashMap();
                masterMap = Maps.newHashMap();
            }
            // 查询厂商信息-录单员
//            ResponseDTO<List<FactoryDRO>> fcFactoryDROResponseDTO = factoryListRemoteService.listByQuery(new FactoryQueryDIO());
//            fcMap = fcFactoryDROResponseDTO.getData().stream().collect(Collectors.toMap(FactoryDRO::getFactoryId, FactoryDRO::getCompanyName, (k1, k2) -> k1));
            fcMap = Maps.newHashMap();
        } else {
            staffMap = Maps.newHashMap();
            masterMap = Maps.newHashMap();
            fcMap = Maps.newHashMap();
        }

        // 业务线名称缓存
        HashMap<Integer, String> bizLineMap = Maps.newHashMap();

        sheet1.setCallback((fieldName, entity) -> {
            EsOrderWorkContact contact = entity.getContact();
            List<EsOrderWorkProduct> productList = entity.getProductList();
            EsOrderWorkFactory factory = entity.getFactoryOrder();
            List<EsOrderNonstandard> orderNonstandardList = Lists.newArrayList();
            Map<Integer, EsOrderAttachment> esOrderAttachmentMap = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(entity.getOrderNonstandardList())) {
                orderNonstandardList = entity.getOrderNonstandardList().stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty((entity.getOrderAttachmentList()))) {
                esOrderAttachmentMap = entity.getOrderAttachmentList().stream().collect(Collectors.toMap(EsOrderAttachment::getType, (e -> e), (key1, key2) -> key2));
            }
            switch (fieldName) {
                case "platCallback":
                    if (entity.getPlat() != null) {
                        return GlobalConsts.getPlatName(entity.getPlat());
                    }
                    break;
                case "platWorkCallback":
                    if (entity.getPlatWork() != null) {
                        return GlobalConsts.getPlatName(entity.getPlatWork());
                    }
                    break;
                case "cancelTimeCallback":
                    Date cancelTime = entity.getCancelTime();
                    if (Objects.nonNull(cancelTime)) {
                        return DateUtil.dateFormatToString(cancelTime, DateUtil.FORMAT_DEFAULT);
                    }
                    break;
                case "addressCallback":
                    if (contact != null) {
                        String street = contact.getStreet();
                        String address = contact.getAddress();
                        return StringUtils.defaultString(street) + (showTel ? "****" : StringUtils.defaultString(address));
                    }
                    return null;
                case "userNameCallback":
                    if (contact != null && contact.getUserName() != null) {
                        return entity.getContact().getUserName();
                    }
                    return null;
                case "serviceProviderCallback":
                    return entity.getManageCompanyName();
                case "userPhoneNameCallback":
                    if (contact != null && contact.getPhone() != null) {
                        String[] phone = entity.getContact().getPhone();
                        return showTel ? phone[0] : MobileUtil.formatHideTel(phone[0]);
                    }
                    return null;
                case "genderCallback":
                    if (contact != null && contact.getGender() != null) {
                        String gender = GlobalDict.getGender(contact.getGender());
                        return gender;
                    }
                    return null;
                case "factoryCallback":
                    if (factory != null) {
                        return entity.getChannelName();
                    }
                    return null;
                case "factoryProductCallback":
                    if (factory != null) {
                        return factory.getProductName();
                    }
                    return null;
                case "bizTypeCallback":
                    return OrderConsts.getOrderBizType(entity.getBizType());
                case "bizLineCallback":
                    if (NumberUtil.isNotNullOrZero(entity.getBizLine())) {
                        // 业务线处理
                        String bizLineName = bizLineMap.get(entity.getBizLine());
                        if (Objects.nonNull(bizLineName)) {
                            return bizLineName;
                        }

                        ResponseDTO<Option<Integer>> nameVtRsp = productBusinessLineForeignListRemoteService.getOptionNameById(entity.getBizLine());
                        Option<Integer> vtDTO = nameVtRsp.getData();
                        if (Objects.nonNull(vtDTO)) {
                            bizLineMap.put(entity.getBizLine(), vtDTO.getLabel());
                            return vtDTO.getLabel();
                        }
                    }
                    return null;
                case "masterNameCallback":
                    String masterName = entity.getMasterName();
                    if (StringUtil.isNotBlank(masterName)) {
                        masterName = String.format("%s:%s", masterName, (showTel ? entity.getMasterPhone() : MobileUtil.formatHideTel(entity.getMasterPhone())));
                    }
                    if (CollectionUtils.isNotEmpty(entity.getMasterList())) {
                        EsOrderWorkMaster esOrderWorkMaster = entity.getMasterList().stream().filter(item -> Objects.equals(item.getMasterId(), entity.getMasterId())).findAny().orElse(null);
                        if (Objects.nonNull(esOrderWorkMaster) && NumberUtil.isNotNullOrZero(esOrderWorkMaster.getStarLevel())) {
                            masterName = String.format("%s（%s星）", masterName, esOrderWorkMaster.getStarLevel());
                        }
                    }
                    return masterName;
                case "cancelLiableNameCallback":
                    String cancelLiableMasterName = entity.getCancelLiableMasterName();
                    Integer cancelLiableMasterId = entity.getCancelLiableMasterId();
                    if (StringUtil.isNotBlank(cancelLiableMasterName)) {
                        return cancelLiableMasterId + "/" + cancelLiableMasterId;
                    } else {
                        return null;
                    }
                case "slaveMasterNameCallback":
                    List<EsOrderWorkMaster> masterList = entity.getMasterList();
                    if (!CollectionUtils.isEmpty(masterList)) {
                        StringBuilder strb = new StringBuilder();
                        masterList.forEach(e -> {
                            if (Objects.equals(OrderConsts.ORDER_MASTER_TYPE_SLAVE, e.getMasterType())) {
                                strb.append(StringUtils.defaultString(e.getMasterName()));
                                strb.append(":");
                                strb.append(showTel ? e.getMasterPhone() : MobileUtil.formatHideTel(e.getMasterPhone()));
                                if (NumberUtil.isNotNullOrZero(e.getStarLevel())) {
                                    strb.append("（").append(e.getStarLevel()).append("星）");
                                }
                                strb.append(";");
                            }
                        });
                        return strb.toString();
                    }
                    break;
                case "reworkMasterNameCallback":
                    String reworkMasterName = entity.getReworkMasterName();
                    if (StringUtil.isNotBlank(reworkMasterName)) {
                        return reworkMasterName + ":" + (showTel ? entity.getReworkMasterPhone() : MobileUtil.formatHideTel(entity.getReworkMasterPhone()));
                    }
                    break;
                case "masterSupervisorNameCallback":
                    String masterSupervisorName = entity.getMasterSupervisorName();
                    if (StringUtil.isNotBlank(masterSupervisorName)) {
                        return masterSupervisorName + ":" + (showTel ? entity.getMasterSupervisorPhone() : MobileUtil.formatHideTel(entity.getMasterSupervisorPhone()));
                    }
                    break;
                case "showProductCallback":
                    if (!CollectionUtils.isEmpty(productList)) {
                        EsOrderWorkProduct esOrderWorkProduct = productList.get(0);
                        return esOrderWorkProduct.getShowProductName();
                    }
                    break;
                case "productCallback":
                    if (!CollectionUtils.isEmpty(productList)) {
                        EsOrderWorkProduct esOrderWorkProduct = productList.get(0);
                        return esOrderWorkProduct.getProductName();
                    }
                    break;
                case "standardPriceCallback":
                    Boolean isStandardPrice = entity.getIsStandardPrice();
                    String isStandardPriceStr;
                    if (isStandardPrice != null && isStandardPrice) {
                        isStandardPriceStr = "是";
                    } else {
                        isStandardPriceStr = "否";
                    }
                    return isStandardPriceStr;
                case "finalPriceRateCallback":
                    String finalPriceRateStr;
                    // 是一口价
                    boolean finalPrice = isFinalPrice(entity);
                    finalPriceRateStr = finalPrice ? "是" : "否";
                    return finalPriceRateStr;
                case "productUnitCallback":
                    if (!CollectionUtils.isEmpty(productList)) {
                        EsOrderWorkProduct esOrderWorkProduct = productList.get(0);
                        return esOrderWorkProduct.getProductUnit();
                    }
                    break;
                case "productBrandCallback":
                    if (!CollectionUtils.isEmpty(productList)) {
                        EsOrderWorkProduct esOrderWorkProduct = productList.get(0);
                        return esOrderWorkProduct.getBrandName();
                    }
                    break;
                case "productNumCallback":
                    if (!CollectionUtils.isEmpty(productList)) {
                        EsOrderWorkProduct esOrderWorkProduct = productList.get(0);
                        return esOrderWorkProduct.getNumber();
                    }
                    break;
                case "originalIdCallback":
                    return (entity.getOriginalId() != null && entity.getOriginalId() != 0) ? String.valueOf(entity.getOriginalId()) : "";
                case "originalAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getOriginalAmount());
                case "discountAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getDiscountAmount());
                case "totalAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getTotalAmount());
                case "channelPrepayAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getChannelPrepayAmount());
                case "depositAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getDepositAmount());
                case "masterAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getMasterAmount());
                case "refundAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getRefundAmount());
                case "channelAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getChannelAmount());
                case "receiveEntranceNameCallback":
                    return StringUtils.defaultString(GateTypeConsts.GATE_NAME_MAP.get(entity.getReceiveEntranceId()));
                case "receiverTypeCallback":
                    String strReceiverId = String.valueOf(entity.getReceiverId());
                    if (strReceiverId.length() == 18) {
                        return "个人用户";
                    }
                    String receiverTypeName = GlobalConsts.getOperatorTypeName(entity.getReceiverType());
                    if (Objects.equals(receiverTypeName, "未知")) {
                        return "其他";
                    }
                    if (Objects.equals(receiverTypeName, "师傅")) {
                        return "工程师";
                    }
                    return receiverTypeName;
                case "receiverNameCallBack":
                    Long receiverId = entity.getReceiverId();
                    Integer type = entity.getReceiverType();

                    if (!NumberUtil.isNullOrZero(receiverId)) {
                        if (receiverId == GlobalConsts.OPERATE_USER_TYPE_SYSTEM) {
                            return "系统";
                        } else if (fcMap.containsKey(receiverId.intValue())) {
                            return fcMap.get(receiverId.intValue());
                        } else if (staffMap.containsKey(receiverId.intValue())) {
                            return staffMap.get(receiverId.intValue());
                        } else if (masterMap.containsKey(receiverId.intValue())) {
                            return masterMap.get(receiverId.intValue());
                        } else if (Objects.equals(GlobalConsts.OPERATE_USER_TYPE_USER, type)) {
                            return "用户";
                        } else {
                            if (String.valueOf(receiverId).length() == 18) {
                                if (contact != null && contact.getUserName() != null) {
                                    return entity.getContact().getUserName();
                                }
                                return null;
                            }
                            return "系统";
                        }
                    } else {
                        return "其它";
                    }

                case "orderNonstandardTitleOneCallback":
                    if (CollectionUtils.isNotEmpty(orderNonstandardList)) {
                        return orderNonstandardList.get(0).getTitle();
                    }
                    break;
                case "orderNonstandardContentOneCallback":
                    if (CollectionUtils.isNotEmpty(orderNonstandardList)) {
                        return orderNonstandardList.get(0).getContent();
                    }
                    break;
                case "orderNonstandardTitleTwoCallback":
                    if (CollectionUtils.isNotEmpty(orderNonstandardList) && orderNonstandardList.size() > 1) {
                        return orderNonstandardList.get(1).getTitle();
                    }
                    break;
                case "orderNonstandardContentTwoCallback":
                    if (CollectionUtils.isNotEmpty(orderNonstandardList) && orderNonstandardList.size() > 1) {
                        return orderNonstandardList.get(1).getContent();
                    }
                    break;
                case "orderNonstandardTitleThreeCallback":
                    if (CollectionUtils.isNotEmpty(orderNonstandardList) && orderNonstandardList.size() > 2) {
                        return orderNonstandardList.get(2).getTitle();
                    }
                    break;
                case "orderNonstandardContentThreeCallback":
                    if (CollectionUtils.isNotEmpty(orderNonstandardList) && orderNonstandardList.size() > 2) {
                        return orderNonstandardList.get(2).getContent();
                    }
                    break;
                case "modifyTypeCallback":
                    if (NumberUtil.isNotNullOrZero(entity.getDistributeModifyCount()) && entity.getDistributeModifyCount() > 1) {
                        return "改派（" + entity.getDistributeModifyCount() + "）";
                    } else if (NumberUtil.isNotNullOrZero(entity.getDutyTimeModifyCount()) && entity.getDutyTimeModifyCount() > 0) {
                        return "改约（" + entity.getDutyTimeModifyCount() + "）";
                    }
                    break;
                case "preConstructionPictureCallback":
                    if (Objects.nonNull(esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_SGQ))) {
                        EsOrderAttachment esOrderAttachment = esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_SGQ);
                        return OrderAttachmentConsts.getReviewResultName(esOrderAttachment.getReviewStatus());
                    }
                    break;
                case "afterCompletionPictureCallback":
                    if (Objects.nonNull(esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_WGH))) {
                        EsOrderAttachment esOrderAttachment = esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_WGH);
                        return OrderAttachmentConsts.getReviewResultName(esOrderAttachment.getReviewStatus());
                    }
                    break;
                case "masterImageCallback":
                    if (Objects.nonNull(entity.getMasterImageStatus())) {
                        return OrderAttachmentConsts.getReviewResultName(entity.getMasterImageStatus());
                    }
                    break;
                case "appliqueImageCallback":
                    if (Objects.nonNull(entity.getAppliqueStatus())) {
                        return OrderAttachmentConsts.getReviewResultName(entity.getAppliqueStatus());
                    }
                    break;
                default:
                    break;
            }
            return null;
        });
        sheet1.builderData();

        if (Objects.equals(supportServiceItem, Boolean.TRUE)) {
            List<ZsOrderWorkServiceItemExportVO> serviceItemExportList = zsOrderWorkQueryBService.converterOrderWorkServiceItemExportVO(orderWorkList);
            ExportExcelBuilder.ExcelSheet<ZsOrderWorkServiceItemExportVO> sheet2 = excel.createExcelSheet("服务项目", serviceItemExportList, sheetTwoMap, true);
            sheet2.setCallback((fieldName, entity) -> {
                switch (fieldName) {
                    case "masterNameCallback":
                        String masterName = entity.getMasterName();
                        if (StringUtil.isNotBlank(masterName)) {
                            return masterName + ":" + entity.getMasterPhone();
                        }
                        break;
                    case "originalAmountCallback":
                        return MoneyUtil.parseToYuanStr(entity.getOriginalAmount());
                    case "discountAmountCallback":
                        return MoneyUtil.parseToYuanStr(entity.getDiscountAmount());
                    case "totalAmountCallback":
                        return MoneyUtil.parseToYuanStr(entity.getTotalAmount());
                    case "serviceItemPriceCallback":
                        return MoneyUtil.parseToYuanStr(entity.getServiceItemPrice());
                    default:
                        break;
                }
                return null;
            });
            sheet2.builderData();
        }
        return excel;
    }

    /**
     * 异步导出工单列表
     *
     * @param query
     */
    @Override
    public void asyncExportListOrderWorkByQuery(OrderWorkQuery query) {
        ResponseDTO<String> exportToken = exportModifyRemoteService.getExportToken(query.getExportTaskId());
        if (!exportToken.isSuccess() || Objects.isNull(exportToken.getData())) {
            logger.info("异步导出获取Token失败，taskId={}", query.getExportTaskId());
            return;
        }
        List<EsOrderWork> orderWorkList = zsOrderWorkQueryBService.exportListOrderWorkByQuery(query);
        // 解密用户地址和电话
        orderEncryptService.batchDecryptEsOrderWork(orderWorkList, EncryptFieldTypeEnum.USER_TELPHONE, EncryptFieldTypeEnum.USER_ADDRESS);
        List<SheetDIO> sheetDIOList = Lists.newArrayListWithCapacity(2);
        SheetDIO sheetOne = SheetDIO.builder()
                .sheetName(ORDER_SHEET_ONE_NAME)
                .build();
        SheetDIO sheetTwo = SheetDIO.builder()
                .sheetName(ORDER_SHEET_TWO_NAME)
                .build();

        Map<Integer, String> staffMap;
        Map<Integer, String> fcMap;
        Map<Integer, String> masterMap;
        Map<Integer, String> sourceChannelMap = null;

        // 业务线名称缓存
        HashMap<Integer, String> bizLineMap = Maps.newHashMap();

        // 录单人处理
        List<Integer> receiverIdList = orderWorkList.stream().
                filter(orderWork -> orderWork.getReceiverId() != null
                        && (GlobalConsts.OPERATE_USER_TYPE_SYSTEM != orderWork.getReceiverId())). //剔除系统和null
                map(orderWork -> orderWork.getReceiverId().intValue()).
                collect(Collectors.toList());
        // 查询员工信息-录单员
        if (receiverIdList.size() > 0) {
            if (receiverIdList.size() > 100) {
                List<List<Integer>> partition = Lists.partition(receiverIdList, 100);
                List<StaffDRO> staffDROList = Lists.newArrayListWithExpectedSize(receiverIdList.size());
                List<ForeignEngineerDetailInfoDRO> baseEngineerDROList = Lists.newArrayListWithExpectedSize(receiverIdList.size());
                partition.stream().forEach(item -> {
                    // 查询来源渠道信息
                    ResponseDTO<List<StaffDRO>> staffList = staffListRemoteService.listStaffByStaffIds(item, null);
                    if (CollectionUtils.isNotEmpty(staffList.getData())) {
                        staffDROList.addAll(staffList.getData());
                    }
                    // todo fubiao
                    logger.info("asyncExportListOrderWorkByQuery#listEngineerDetailByIdSet start [{}]",JSON.toJSONString(item));
                    ResponseDTO<List<ForeignEngineerDetailInfoDRO>> responseDTO = engineerListRemoteService.listEngineerDetailByIdSet(new HashSet<>(item));
                    logger.info("asyncExportListOrderWorkByQuery#listEngineerDetailByIdSet end [{}]",JSON.toJSONString(responseDTO));
                    if (CollectionUtils.isNotEmpty(responseDTO.getData())) {
                        baseEngineerDROList.addAll(responseDTO.getData());
                    }
                });
                staffMap = staffDROList.stream()
                        .collect(Collectors.toMap(StaffDRO::getStaffId, StaffDRO::getRealName, (oldVal, newVal) -> oldVal));
                masterMap = baseEngineerDROList.stream().
                        collect(Collectors.toMap(ForeignEngineerDetailInfoDRO::getEngineerId, ForeignEngineerDetailInfoDRO::getRealName, (k1, k2) -> k1));
            } else {
                ResponseDTO<List<StaffDRO>> staffList = staffListRemoteService.listStaffByStaffIds(receiverIdList, null);
                staffMap = staffList.getData().stream().collect(Collectors.toMap(StaffDRO::getStaffId, StaffDRO::getRealName, (k1, k2) -> k1));

                // todo fubiao
                logger.info("asyncExportListOrderWorkByQuery#listEngineerDetailByIdSet start [{}]",JSON.toJSONString(receiverIdList));
                ResponseDTO<List<ForeignEngineerDetailInfoDRO>> responseDTO = engineerListRemoteService.listEngineerDetailByIdSet(new HashSet<>(receiverIdList));
                logger.info("asyncExportListOrderWorkByQuery#listEngineerDetailByIdSet end [{}]",JSON.toJSONString(responseDTO));
                if (!responseDTO.isSuccess() || CollectionUtils.isEmpty(responseDTO.getData())) {
                    masterMap = Maps.newHashMap();
                } else {
                    List<ForeignEngineerDetailInfoDRO> items = responseDTO.getData();
                    masterMap = items.stream().collect(Collectors.toMap(ForeignEngineerDetailInfoDRO::getEngineerId, ForeignEngineerDetailInfoDRO::getRealName, (k1, k2) -> k1));
                }
            }
        } else {
            staffMap = Maps.newHashMap();
            masterMap = Maps.newHashMap();
        }
        // 查询厂商信息-录单员
//        ResponseDTO<List<FactoryDRO>> fcFactoryDROResponseDTO = factoryListRemoteService.listByQuery(new FactoryQueryDIO());
//        fcMap = fcFactoryDROResponseDTO.getData().stream()
//                .collect(Collectors.toMap(FactoryDRO::getFactoryId, FactoryDRO::getCompanyName, (k1, k2) -> k1));
        fcMap = Maps.newHashMap();
        List<List<String>> sheetOneList = Lists.newArrayListWithCapacity(orderWorkList.size() + 1);
        sheetOneList.add(sheetOneFirstRowList);

        String pattern = "yyyy-MM-dd HH:mm";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        ZoneId zoneId = ZoneId.systemDefault();

        // 来源渠道处理
        List<Integer> sourceChannelIds = orderWorkList.stream()
                .filter(orderWork -> orderWork.getSourceChannelId() != null)
                .map(orderWork -> orderWork.getSourceChannelId())
                .collect(Collectors.toList());

        logger.info("来源id集合 sourceChannelIds：{}", sourceChannelIds);
        if (CollectionUtil.isNotNullOrEmpty(sourceChannelIds)) {
            List<Integer> collect = sourceChannelIds.stream().distinct().collect(Collectors.toList());
            logger.info("去重之后的来源id集合 collect：{}", collect);

            if (collect.size() > 100) {
                List<List<Integer>> partition = Lists.partition(collect, 100);
                List<ChannelDRO> channelDROList = Lists.newArrayListWithExpectedSize(sourceChannelIds.size());
                logger.info("工单导出查询来源渠道信息，partition：{}", partition);
                partition.stream().forEach(item->{
                    // 查询来源渠道信息
                    ResponseDTO<List<ChannelDRO>> sourceChannelDROResponseDTO = channelListRemoteService.listByChannelIds(item);
                    logger.info("查询来源渠道信息 ，item：{} ， sourceChannelDROResponseDTO：{}", item, sourceChannelDROResponseDTO);
                    if (CollectionUtils.isNotEmpty(sourceChannelDROResponseDTO.getData())) {
                        channelDROList.addAll(sourceChannelDROResponseDTO.getData());
                    }
                });
                sourceChannelMap = channelDROList.stream()
                        .collect(Collectors.toMap(ChannelDRO::getChannelId, ChannelDRO::getName, (oldVal, newVal) -> oldVal));
            } else {
                ResponseDTO<List<ChannelDRO>> sourceChannelDROResponseDTO = channelListRemoteService.listByChannelIds(collect);
                if (sourceChannelDROResponseDTO.isSuccess() || !Objects.isNull(sourceChannelDROResponseDTO.getData())) {
                    sourceChannelMap = sourceChannelDROResponseDTO.getData().stream()
                            .collect(Collectors.toMap(ChannelDRO::getChannelId, ChannelDRO::getName, (oldVal, newVal) -> oldVal));
                }
            }
        }

        logger.info("来源渠道 map：{}", sourceChannelMap);
        if (Objects.isNull(sourceChannelMap)) {
            sourceChannelMap = Maps.newHashMap();
        }

        // 打款人处理
        Map<Integer, String> remitPeopleMap;
        List<Integer> remitPeopleList = new ArrayList<>(orderWorkList.stream()
                .filter(e -> Objects.nonNull(e.getRefundDetail()))
                .map(EsOrderWork::getRefundDetail)
                .filter(e -> Objects.nonNull(e.getRemitPeople()))
                .filter(e -> !Objects.equals(e.getRemitPeople(), GlobalConsts.NONE))
                .map(EsOrderWorkRefundDetail::getRemitPeople)
                .map(Long::intValue)
                .collect(Collectors.toSet()));

        if (CollectionUtils.isNotEmpty(remitPeopleList)) {
            ResponseDTO<List<StaffDRO>> staffList = staffListRemoteService.listStaffByStaffIds(remitPeopleList, null);
            remitPeopleMap = staffList.getData().stream().collect(Collectors.toMap(StaffDRO::getStaffId, StaffDRO::getRealName, (k1, k2) -> k1));
        } else {
            remitPeopleMap = Maps.newHashMap();
        }

        // 处理临时小号
        Map<Long, OrderXnoBind> tempXnoMap = Maps.newHashMap();
        List<Long> workIdList = orderWorkList.stream().map(orderWork -> orderWork.getId()).collect(Collectors.toList());
        List<OrderXnoBind> xnoCountList = orderXnoService.queryOrderXnoBindByWorkIdList(workIdList, OrderXnoConsts.BIND_TYPE_TEMP);
        if (CollectionUtil.isNotNullOrEmpty(xnoCountList)) {
            tempXnoMap = xnoCountList.stream().collect(Collectors.toMap(OrderXnoBind::getWorkId, (e -> e), (a, e) -> e));
        }

        Map<Long, List<OrderChannelPrepay>> tempChannelPrepay = Maps.newHashMap();
        List<OrderChannelPrepay> channelPrepayList = orderChannelPrepayService.listOrderChannelPrepayByWorkIdList(workIdList);
        if (CollectionUtil.isNotNullOrEmpty(channelPrepayList)) {
            tempChannelPrepay = channelPrepayList.stream().collect(Collectors.groupingBy(OrderChannelPrepay::getWorkId));
        }

        for (EsOrderWork esOrderWork : orderWorkList) {
            List<String> sheetOneRowList = Lists.newArrayListWithCapacity(sheetOneSize);
            EsOrderWorkContact contact = esOrderWork.getContact();
            List<EsOrderWorkProduct> productList = esOrderWork.getProductList();
            EsOrderWorkFactory factory = esOrderWork.getFactoryOrder();
            List<EsOrderNonstandard> orderNonstandardList = Lists.newArrayList();
            Map<Integer, EsOrderAttachment> esOrderAttachmentMap = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(esOrderWork.getOrderNonstandardList())) {
                orderNonstandardList = esOrderWork.getOrderNonstandardList().stream().filter(e -> e.getType() == 1)
                        .collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(esOrderWork.getOrderAttachmentList())) {
                esOrderAttachmentMap = esOrderWork.getOrderAttachmentList().stream().collect(Collectors.toMap(EsOrderAttachment::getType, (e -> e), (key1, key2) -> key2));
            }
            sheetOneRowList.add(esOrderWork.getPlat() == null ? "" : GlobalConsts.getPlatName(esOrderWork.getPlat()));
            sheetOneRowList.add(esOrderWork.getReceiveTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getReceiveTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getFirstDutyTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getFirstDutyTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getFirstDutyOptTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getFirstDutyOptTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getLastDutyTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getLastDutyTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getLastDutyOptTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getLastDutyOptTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getSuspendTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getSuspendTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getDistributeTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getDistributeTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getVisitTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getVisitTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getCancelTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getCancelTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getServiceCompleteTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getServiceCompleteTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getCompleteTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getCompleteTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getAccountTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getAccountTime().toInstant(), zoneId)));
            sheetOneRowList.add(esOrderWork.getChannelStatementCanTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(esOrderWork.getChannelStatementCanTime().toInstant(), zoneId)));

            sheetOneRowList.add(String.valueOf(esOrderWork.getId()));
            sheetOneRowList.add(esOrderWork.getExtOuterId());
            sheetOneRowList.add(esOrderWork.getExtOuterSubId());

            // TODO 子公司 如果执行子公司ID是0或者null就用行政子公司 反之则执行子公司
            String subCompanyName;
            if (NumberUtil.isNullOrZero(esOrderWork.getCompanyId())) {
                subCompanyName = esOrderWork.getGridCompanyName();
            } else {
                subCompanyName = esOrderWork.getCompanyName();
            }

	        sheetOneRowList.add(subCompanyName);
            // 省份
            sheetOneRowList.add(esOrderWork.getProvinceName());
            sheetOneRowList.add(esOrderWork.getNaturalCityName());
            sheetOneRowList.add(esOrderWork.getCountyName());
            // 用户信息
            String addr = "";
            String userName = "";
            String userPhone = "";
            String gender = "";
            if (Objects.nonNull(contact)) {
                // 用户地址
                if (query.getIsSensitiveAddr()) {
                    addr = String.join("", StringUtils.defaultString(contact.getStreet()), "****");
                } else {
                    addr = String.join("", StringUtils.defaultString(contact.getStreet()), StringUtils.defaultString(contact.getAddress()));
                }

                // 用户姓名
                userName = StringUtils.defaultString(contact.getUserName());

                // 用户电话
                if (contact.getPhone() != null) {
                    String[] phone = contact.getPhone();
                    userPhone = query.getIsSensitiveTel() ? MobileUtil.formatHideTel(phone[0]) : phone[0];
                }

                // 用户性别
                if (contact.getGender() != null) {
                    gender = GlobalDict.getGender(contact.getGender());
                }
            }
            sheetOneRowList.add(addr);
            sheetOneRowList.add(userName);
            sheetOneRowList.add(userPhone);
            sheetOneRowList.add(gender);

            // 厂商信息
            String channelName = "";
            String factoryProductName = "";
            if (Objects.nonNull(factory)) {
                channelName = esOrderWork.getChannelName();
                factoryProductName = factory.getProductName();
            }
            sheetOneRowList.add(channelName);
            sheetOneRowList.add(factoryProductName);

            // 业务类型
            sheetOneRowList.add(OrderConsts.getOrderBizType(esOrderWork.getBizType()));
            sheetOneRowList.add(this.processBizLine(esOrderWork.getBizLine(), bizLineMap));
            sheetOneRowList.add(esOrderWork.getServProductGroupName());
            sheetOneRowList.add(esOrderWork.getServCategName());
            // 产品信息
            String showProductName = "";
            String productName = "";
            String productUnit = "";
            String productBrand = "";
            String productNum = "";
            if (CollectionUtils.isNotEmpty(productList)) {
                EsOrderWorkProduct esOrderWorkProduct = productList.get(0);
                showProductName = esOrderWorkProduct.getShowProductName();
                productName = esOrderWorkProduct.getProductName();
                productUnit = esOrderWorkProduct.getProductUnit();
                productBrand = esOrderWorkProduct.getBrandName();
                productNum = String.valueOf(esOrderWorkProduct.getNumber());
            }
            sheetOneRowList.add(showProductName);
            sheetOneRowList.add(productName);
            sheetOneRowList.add(productUnit);
            sheetOneRowList.add(productBrand);
            sheetOneRowList.add(productNum);
            sheetOneRowList.add(esOrderWork.getTypeName());

            // 标准收费单
            Boolean isStandardPrice = esOrderWork.getIsStandardPrice();
            String isStandardPriceStr;
            if (isStandardPrice != null && isStandardPrice) {
                isStandardPriceStr = "是";
            } else {
                isStandardPriceStr = "否";
            }
            sheetOneRowList.add(isStandardPriceStr);

            // 是否一口价
            boolean finalPrice = isFinalPrice(esOrderWork);
            String finalPriceRateStr = finalPrice ? "是" : "否";
            sheetOneRowList.add(finalPriceRateStr);

            sheetOneRowList.add((esOrderWork.getOriginalId() != null && esOrderWork.getOriginalId() != 0) ? String.valueOf(esOrderWork.getOriginalId()) : "");
            sheetOneRowList.add(esOrderWork.getFaultContent());
            sheetOneRowList.add(esOrderWork.getRemark());
            // 服务平台
            sheetOneRowList.add(esOrderWork.getPlatWork() == null ? "" : GlobalConsts.getPlatName(esOrderWork.getPlatWork()));

			// TODO 服务商 如果执行服务商ID是0或者null就用行政服务商 反之则执行服务商
	        String manageCompanyName;
	        if (NumberUtil.isNullOrZero(esOrderWork.getManageCompanyId())) {
		        manageCompanyName = esOrderWork.getGridManageCompanyName();
	        } else {
		        manageCompanyName = esOrderWork.getManageCompanyName();
	        }
	        sheetOneRowList.add(manageCompanyName);

            // 工程师信息
            String masterName = esOrderWork.getMasterName();
            if (StringUtil.isNotBlank(masterName)) {
                masterName = masterName + ":" + (query.getIsSensitiveTel() ? MobileUtil.formatHideTel(esOrderWork.getMasterPhone()) : esOrderWork.getMasterPhone());
                if (CollectionUtils.isNotEmpty(esOrderWork.getMasterList())) {
                    EsOrderWorkMaster esOrderWorkMaster = esOrderWork.getMasterList().stream().filter(item -> Objects.equals(item.getMasterId(), esOrderWork.getMasterId())).findAny().orElse(null);
                    if (Objects.nonNull(esOrderWorkMaster) && NumberUtil.isNotNullOrZero(esOrderWorkMaster.getStarLevel())) {
                        masterName = String.format("%s（%s星）", masterName, esOrderWorkMaster.getStarLevel());
                    }
                }
            }
            sheetOneRowList.add(masterName);
            //责任工程师
            sheetOneRowList.add(Objects.nonNull(esOrderWork.getCancelLiableMasterName()) ? esOrderWork.getCancelLiableMasterName() + "/" + esOrderWork.getCancelLiableMasterId() : "");

            String slaveMasterName = "";
            List<EsOrderWorkMaster> masterList = esOrderWork.getMasterList();
            if (!CollectionUtils.isEmpty(masterList)) {
                StringBuilder strb = new StringBuilder();
                masterList.forEach(e -> {
                    if (Objects.equals(OrderConsts.ORDER_MASTER_TYPE_SLAVE, e.getMasterType())) {
                        strb.append(StringUtils.defaultString(e.getMasterName()));
                        strb.append(":");
                        strb.append(query.getIsSensitiveTel() ? MobileUtil.formatHideTel(e.getMasterPhone()) : e.getMasterPhone());
                        if (NumberUtil.isNotNullOrZero(e.getStarLevel())) {
                            strb.append("（").append(e.getStarLevel()).append("星）");
                        }
                        strb.append(";");
                    }
                });
                slaveMasterName = strb.toString();
            }
            sheetOneRowList.add(slaveMasterName);

            String masterSupervisorName = esOrderWork.getMasterSupervisorName();
            if (StringUtil.isNotBlank(masterSupervisorName)) {
                masterSupervisorName = masterSupervisorName + ":" + (query.getIsSensitiveTel() ? MobileUtil.formatHideTel(esOrderWork.getMasterSupervisorPhone()) : esOrderWork.getMasterSupervisorPhone());
            }
            sheetOneRowList.add(masterSupervisorName);

            String reworkMasterName = esOrderWork.getReworkMasterName();
            if (StringUtil.isNotBlank(reworkMasterName)) {
                reworkMasterName = reworkMasterName + ":" + (query.getIsSensitiveTel() ? MobileUtil.formatHideTel(esOrderWork.getReworkMasterPhone()) : esOrderWork.getReworkMasterPhone());
            }
            sheetOneRowList.add(reworkMasterName);

            sheetOneRowList.add(esOrderWork.getStatusName());
            sheetOneRowList.add(esOrderWork.getResultStatusName());
            // 金额信息
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getOriginalAmount()));
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getPrepayAmount()));
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getDiscountAmount()));

            String itemIds = "";
            String sourceIds = "";
            List<EsOrderWorkDiscount> discountList = esOrderWork.getDiscountList();
            if (CollectionUtils.isNotEmpty(discountList)) {
                // 规则ID
                itemIds = discountList.stream()
                        .filter(orderDiscount -> NumberUtil.isNotNullOrZero(orderDiscount.getItemId()) &&
                                (Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_RULE_COMMON.getSubType())
                                || Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_RULE_ARTIFICIAL.getSubType())
                                || Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_ACTIVITY_LATE_COMPENSATE.getSubType())
                                || Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_FREE.getSubType()))
                        )
                        .map(EsOrderWorkDiscount::getItemId)
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));

                sourceIds = discountList.stream()
                        .filter(orderDiscount -> NumberUtil.isNotNullOrZero(orderDiscount.getSourceId()) &&
                                (Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_COUP_COMMON.getSubType())
                                || Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_COUP_VOUCHER.getSubType())
                                || Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_CHANNEL.getSubType())
                                || Objects.equals(orderDiscount.getDiscountCateg(), DiscountTypeEnums.DISCOUNT_COUP_CASH.getSubType()))
                        )
                        .map(EsOrderWorkDiscount::getSourceId)
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));
            }

            // 优惠规则id
            sheetOneRowList.add(itemIds);
            // 优惠券批次id
            sheetOneRowList.add(sourceIds);
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getTotalAmount()));
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getChannelPrepayAmount()));
            // 渠道预付明细
            List<OrderChannelPrepay> prepayList = tempChannelPrepay.get(esOrderWork.getId());
            if (CollectionUtil.isNullOrEmpty(prepayList)) {
                if (NumberUtil.isNullOrZero(esOrderWork.getChannelPrepayAmount())) {
                    sheetOneRowList.add("");
                } else {
                    sheetOneRowList.add("实收金额：" + MoneyUtil.parseToYuanStartWithUnit(esOrderWork.getChannelPrepayAmount()));
                }
            } else {
                int sum = prepayList.stream().mapToInt(OrderChannelPrepay::getAmount).sum();
                StringJoiner sj = new StringJoiner("，");
                sj.add("实收金额：" + MoneyUtil.parseToYuanStartWithUnit(esOrderWork.getChannelPrepayAmount() - sum));
                prepayList.forEach(e -> {
                    sj.add(e.getPrepayTypeName() + "：" + MoneyUtil.parseToYuanStartWithUnit(e.getAmount()));
                });
                sheetOneRowList.add(sj.toString());
            }
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getDepositAmount()));
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getMasterAmount()));
            // 退款单号
            sheetOneRowList.add(Objects.equals(esOrderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) ? String.valueOf(esOrderWork.getId()) : "");
            // 打款日期
            sheetOneRowList.add(Objects.equals(esOrderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) && Objects.nonNull(esOrderWork.getLastRefundAmountTime()) && Objects.equals(esOrderWork.getPayStatus(), PayConsts.REFUND_STATUS_DONE) ? formatter.format(LocalDateTime.ofInstant(esOrderWork.getLastRefundAmountTime().toInstant(), zoneId)) : "");
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getRefundAmount()));
            // 退款单支付状态
            sheetOneRowList.add(Objects.equals(esOrderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) ? PayConsts.getPayStatusName(esOrderWork.getPayStatus()) : "");
            // 退款手续费
            sheetOneRowList.add(Objects.nonNull(esOrderWork.getRefundDetail()) ? MoneyUtil.parseToYuanStr(esOrderWork.getRefundDetail().getRefundPoundage()) : null);
            // 退款缘由
            String refundRemark = "";
            List<EsOrderRemarkDetail> remarkDetailList = esOrderWork.getRemarkDetailList();
            if (CollectionUtils.isNotEmpty(remarkDetailList)) {
                refundRemark = remarkDetailList.stream()
                        .filter(e -> Objects.equals(e.getType(), OrderConsts.ORDER_REMARK_TYPE_REFUND))
                        .map(EsOrderRemarkDetail::getMapName)
                        .collect(Collectors.joining(","));
            }
            sheetOneRowList.add(refundRemark);
            // 退款方式
            sheetOneRowList.add(Objects.nonNull(esOrderWork.getRefundDetail()) ? OrderConsts.getRefundTypeName(esOrderWork.getRefundDetail().getRefundType()) : null);
            // 退款路径
            String refundPath = "";
            if (Objects.nonNull(esOrderWork.getRefundDetail())) {
                EsOrderWorkRefundDetail refundDetail = esOrderWork.getRefundDetail();
                if (Objects.equals(refundDetail.getRefundPath(), GlobalConsts.NONE)) {
                    List<EsVoucherOrder> voucherOrderList = esOrderWork.getVoucherOrderList();
                    if (CollectionUtils.isNotEmpty(voucherOrderList)) {
                        refundPath = voucherOrderList.stream()
                                .filter(e -> Objects.equals(e.getTradeType(), PayConsts.PAY_TRADE_TYPE_REFUND))
                                .filter(e -> Objects.nonNull(e.getPayChannelId()))
                                .map(EsVoucherOrder::getPayChannelId)
                                .map(PayConsts::getPayChannelName)
                                .collect(Collectors.joining(","));

                    }
                } else {
                    refundPath = PayConsts.getPayChannelName(refundDetail.getRefundPath());
                }
            }
            sheetOneRowList.add(refundPath);
            // 支付宝户名 支付宝账号
            if (Objects.nonNull(esOrderWork.getRefundDetail()) && Objects.equals(esOrderWork.getRefundDetail().getRefundPath(), PayConsts.PAY_CHANNEL_PLATFORM_ALIPAY)) {
                sheetOneRowList.add(esOrderWork.getRefundDetail().getPayeeThirdAccountName());
                sheetOneRowList.add(esOrderWork.getRefundDetail().getPayeeThirdAccount());
            } else {
                sheetOneRowList.add("");
                sheetOneRowList.add("");
            }
            // 微信ID 微信姓名
            if (Objects.nonNull(esOrderWork.getRefundDetail()) && Objects.equals(esOrderWork.getRefundDetail().getRefundPath(), PayConsts.PAY_CHANNEL_PLATFORM_WEIXINPAY)) {
                sheetOneRowList.add(esOrderWork.getRefundDetail().getPayeeThirdAccount());
                sheetOneRowList.add(esOrderWork.getRefundDetail().getPayeeThirdAccountName());
            } else {
                sheetOneRowList.add("");
                sheetOneRowList.add("");
            }
            // 银行卡开户行 银行卡号 户名
            if (Objects.nonNull(esOrderWork.getRefundDetail()) && Objects.equals(esOrderWork.getRefundDetail().getRefundPath(), PayConsts.PAY_CHANNEL_PLATFORM_BANKTRANSFER)) {
                sheetOneRowList.add(esOrderWork.getRefundDetail().getPayeeThirdAccountBank());
                sheetOneRowList.add(esOrderWork.getRefundDetail().getPayeeThirdAccount());
                sheetOneRowList.add(esOrderWork.getRefundDetail().getPayeeThirdAccountName());
            } else {
                sheetOneRowList.add("");
                sheetOneRowList.add("");
                sheetOneRowList.add("");
            }
            // 退款单录单人
            String refundReceiver = "";
            if (Objects.equals(esOrderWork.getType(), OrderConsts.ORDER_TYPE_REFUND)) {
                Long receiverId = esOrderWork.getReceiverId();
                Integer type = esOrderWork.getReceiverType();
                if (!NumberUtil.isNullOrZero(receiverId)) {
                    if (receiverId == GlobalConsts.OPERATE_USER_TYPE_SYSTEM) {
                        refundReceiver = "系统";
                    } else if (fcMap.containsKey(receiverId.intValue())) {
                        refundReceiver = fcMap.get(receiverId.intValue());
                    } else if (staffMap.containsKey(receiverId.intValue())) {
                        refundReceiver = staffMap.get(receiverId.intValue());
                    } else if (masterMap.containsKey(receiverId.intValue())) {
                        refundReceiver = masterMap.get(receiverId.intValue());
                    } else if (Objects.equals(GlobalConsts.OPERATE_USER_TYPE_USER, type)) {
                        refundReceiver = "用户";
                    } else {
                        if (String.valueOf(receiverId).length() == 18) {
                            if (contact != null && contact.getUserName() != null) {
                                refundReceiver = esOrderWork.getContact().getUserName();
                            }
                        }
                        refundReceiver = "系统";
                    }
                } else {
                    refundReceiver = "其它";
                }
            }
            sheetOneRowList.add(refundReceiver);
            // 打款人
            sheetOneRowList.add(Objects.isNull(esOrderWork.getRefundDetail()) || Objects.isNull(esOrderWork.getRefundDetail().getRemitPeople()) ? null : remitPeopleMap.get(esOrderWork.getRefundDetail().getRemitPeople().intValue()));

            // 打款银行
            String remitBank = "";
            String refundVoucherNo = "";
            String refundVoucherRemark = "";
            if (!Objects.isNull(esOrderWork.getRefundDetail())) {
                if (StringUtil.isNotBlank(esOrderWork.getRefundDetail().getPayerThirdAccountBank())) {
                    remitBank = String.format("%s-%s", esOrderWork.getRefundDetail().getPayerThirdAccountBank(), esOrderWork.getRefundDetail().getPayerThirdAccount());
                }
                refundVoucherNo = esOrderWork.getRefundDetail().getRefundVoucherNo();
                refundVoucherRemark = esOrderWork.getRefundDetail().getRefundVoucherRemark();
            }
            sheetOneRowList.add(remitBank);
            // 退款凭证号
            sheetOneRowList.add(refundVoucherNo);
            // 退款凭证备注
            sheetOneRowList.add(refundVoucherRemark);
            sheetOneRowList.add(MoneyUtil.parseToYuanStr(esOrderWork.getChannelAmount()));
            sheetOneRowList.add(esOrderWork.getPayStatusName());
            sheetOneRowList.add(esOrderWork.getSuspendContent());
            sheetOneRowList.add(esOrderWork.getFailContent());
            sheetOneRowList.add(esOrderWork.getDiscardContent());
            sheetOneRowList.add(esOrderWork.getChannelName());
            // 来源渠道名称
            sheetOneRowList.add(sourceChannelMap.get(esOrderWork.getSourceChannelId()));
            // 渠道单号
            sheetOneRowList.add(esOrderWork.getOuterId());
            // 执行子公司
            sheetOneRowList.add(esOrderWork.getCompanyName());
            // 行政子公司
            sheetOneRowList.add(esOrderWork.getGridCompanyName());
            // 执行服务商
            sheetOneRowList.add(esOrderWork.getManageCompanyName());
            // 行政服务商
            sheetOneRowList.add(esOrderWork.getGridManageCompanyName());
            sheetOneRowList.add(StringUtils.defaultString(GateTypeConsts.GATE_NAME_MAP.get(esOrderWork.getReceiveEntranceId())));

            String receiverTypeName = "";
            String strReceiverId = String.valueOf(esOrderWork.getReceiverId());
            if (strReceiverId.length() == 18) {
                receiverTypeName = "个人用户";
            }
            receiverTypeName = GlobalConsts.getOperatorTypeName(esOrderWork.getReceiverType());
            if (Objects.equals(receiverTypeName, "未知")) {
                receiverTypeName = "其他";
            }
            if (Objects.equals(receiverTypeName, "师傅")) {
                receiverTypeName = "工程师";
            }
            sheetOneRowList.add(receiverTypeName);
            sheetOneRowList.add(String.valueOf(esOrderWork.getReceiverId()));

            String receiver = "";
            Long receiverId = esOrderWork.getReceiverId();
            Integer type = esOrderWork.getReceiverType();
            if (!NumberUtil.isNullOrZero(receiverId)) {
                if (receiverId == GlobalConsts.OPERATE_USER_TYPE_SYSTEM) {
                    receiver = "系统";
                } else if (fcMap.containsKey(receiverId.intValue())) {
                    receiver = fcMap.get(receiverId.intValue());
                } else if (staffMap.containsKey(receiverId.intValue())) {
                    receiver = staffMap.get(receiverId.intValue());
                } else if (masterMap.containsKey(receiverId.intValue())) {
                    receiver = masterMap.get(receiverId.intValue());
                } else if (Objects.equals(GlobalConsts.OPERATE_USER_TYPE_USER, type)) {
                    receiver = "用户";
                } else {
                    if (String.valueOf(receiverId).length() == 18) {
                        if (contact != null && contact.getUserName() != null) {
                            receiver = esOrderWork.getContact().getUserName();
                        }
                    }
                    receiver = "系统";
                }
            } else {
                receiver = "其它";
            }
            sheetOneRowList.add(receiver);

            // 会员等级
            if (Objects.equals(esOrderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_MEMBER)) {
                // 兼容历史数据
                String memberLevelName = "Z+金卡";
                if (CollectionUtils.isNotEmpty(esOrderWork.getOrderTagList())) {
                    EsOrderTag esOrderTag = esOrderWork.getOrderTagList().stream().filter(item ->
                            Objects.equals(item.getTagId(), OrderTagConsts.TAG_ID_WORK_VAS_MEMBER_LEVEL_1)
                            || Objects.equals(item.getTagId(), OrderTagConsts.TAG_ID_WORK_VAS_MEMBER_LEVEL_2))
                            .findAny().orElse(null);
                    if(esOrderTag != null){
                        memberLevelName = esOrderTag.getTagName();
                    }
                }
                sheetOneRowList.add(memberLevelName);
            } else {
                sheetOneRowList.add("");
            }


            sheetOneRowList.add(esOrderWork.getCommentScore() == null ? "" : String.valueOf(esOrderWork.getCommentScore()));
            sheetOneRowList.add(esOrderWork.getReplyContent());

            // 非标信息
            String titleOne = "";
            String contentOne = "";
            String titleTwo = "";
            String contentTwo = "";
            String titleThree = "";
            String contentThree = "";
            if (CollectionUtils.isNotEmpty(orderNonstandardList)) {
                titleOne = orderNonstandardList.get(0).getTitle();
                contentOne = orderNonstandardList.get(0).getContent();
                if (orderNonstandardList.size() > 1) {
                    titleTwo = orderNonstandardList.get(1).getTitle();
                    contentTwo = orderNonstandardList.get(1).getContent();
                    if (orderNonstandardList.size() > 2) {
                        titleThree = orderNonstandardList.get(2).getTitle();
                        contentThree = orderNonstandardList.get(2).getContent();
                    }
                }
            }
            sheetOneRowList.add(titleOne);
            sheetOneRowList.add(contentOne);
            sheetOneRowList.add(titleTwo);
            sheetOneRowList.add(contentTwo);
            sheetOneRowList.add(titleThree);
            sheetOneRowList.add(contentThree);

            String modifyType = "";
            if (NumberUtil.isNotNullOrZero(esOrderWork.getDistributeModifyCount()) && esOrderWork.getDistributeModifyCount() > 1) {
                modifyType = "改派（" + esOrderWork.getDistributeModifyCount() + "）";
            } else if (NumberUtil.isNotNullOrZero(esOrderWork.getDutyTimeModifyCount()) && esOrderWork.getDutyTimeModifyCount() > 0) {
                modifyType = "改约（" + esOrderWork.getDutyTimeModifyCount() + "）";
            }
            sheetOneRowList.add(modifyType);

            sheetOneRowList.add(Objects.nonNull(esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_SGQ)) ? OrderAttachmentConsts.getReviewResultName(esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_SGQ).getReviewStatus()) : "");
            sheetOneRowList.add(Objects.nonNull(esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_WGH)) ? OrderAttachmentConsts.getReviewResultName(esOrderAttachmentMap.get(OrderAttachmentTypeEnum.CONSTS_WGH).getReviewStatus()) : "");
            sheetOneRowList.add(Objects.nonNull(esOrderWork.getMasterImageStatus()) ? OrderAttachmentConsts.getReviewResultName(esOrderWork.getMasterImageStatus()) : "");
            sheetOneRowList.add(Objects.nonNull(esOrderWork.getAppliqueStatus()) ? OrderAttachmentConsts.getReviewResultName(esOrderWork.getAppliqueStatus()) : "");
            sheetOneRowList.add(StringUtils.defaultString(esOrderWork.getGridName()));
            sheetOneRowList.add(Objects.nonNull(tempXnoMap.get(esOrderWork.getId())) ? "是" : "否");

            sheetOneList.add(sheetOneRowList);
        };

        sheetOne.setExportContents(sheetOneList);

        if (Objects.equals(query.getSupportServiceItem(), Boolean.TRUE)) {
            List<ZsOrderWorkServiceItemExportVO> serviceItemExportList = zsOrderWorkQueryBService.converterOrderWorkServiceItemExportVO(orderWorkList);
            List<List<String>> sheetTwoList = Lists.newArrayListWithCapacity(serviceItemExportList.size() + 1);
            sheetTwoList.add(sheetTwoFirstRowList);
            serviceItemExportList.forEach(item -> {
                List<String> sheetTwoRowList = Lists.newArrayListWithCapacity(sheetTwoSize);
                sheetTwoRowList.add(item.getReceiveTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(item.getReceiveTime().toInstant(), zoneId)));
                sheetTwoRowList.add(item.getCompleteTime() == null ? "" : formatter.format(LocalDateTime.ofInstant(item.getCompleteTime().toInstant(), zoneId)));
                sheetTwoRowList.add(String.valueOf(item.getId()));
                sheetTwoRowList.add(item.getCompanyName());
                sheetTwoRowList.add(item.getNaturalCityName());

                String masterName = item.getMasterName();
                if (StringUtil.isNotBlank(masterName)) {
                    masterName = masterName + ":" + item.getMasterPhone();
                }
                sheetTwoRowList.add(masterName);

                sheetTwoRowList.add(item.getStatusName());
                sheetTwoRowList.add(item.getResultStatusName());
                sheetTwoRowList.add(item.getServCategName());

                sheetTwoRowList.add(MoneyUtil.parseToYuanStr(item.getOriginalAmount()));
                sheetTwoRowList.add(MoneyUtil.parseToYuanStr(item.getDiscountAmount()));
                sheetTwoRowList.add(MoneyUtil.parseToYuanStr(item.getTotalAmount()));

                sheetTwoRowList.add(item.getProductName());
                sheetTwoRowList.add(String.valueOf(item.getProductNum()));
                sheetTwoRowList.add(item.getServiceItemName());
                sheetTwoRowList.add(item.getServiceItemNum() == null ? "" : String.valueOf(item.getServiceItemNum()));
                sheetTwoRowList.add(MoneyUtil.parseToYuanStr(item.getServiceItemPrice()));

                sheetTwoList.add(sheetTwoRowList);
            });

            sheetTwo.setExportContents(sheetTwoList);
        }

        sheetDIOList.add(sheetOne);
        sheetDIOList.add(sheetTwo);

        ExportHttpDIO exportHttpDIO = new ExportHttpDIO();
        exportHttpDIO.setExportTaskId(query.getExportTaskId());
        exportHttpDIO.setToken(exportToken.getData());
        exportHttpDIO.setList(sheetDIOList);
        try {
            logger.debug("[{}]异步导出工单列表入参：【{}】", query.getExportTaskId(), JSON.toJSONString(exportHttpDIO));
            String response = HttpUtil.httpsPost(ZMN_TAPI_EXPORT_URL, JSON.toJSONString(exportHttpDIO));
            logger.info("异步导出工单列表出参，taskId={}，【{}】", query.getExportTaskId(), response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("异步导出工单列表失败：taskId=【{}】失败信息：【{}】", query.getExportTaskId(), e.getMessage());
        }
        //ResponseDTO<Boolean> responseDTO = exportModifyRemoteService.exportMultipleSheetInfo(query.getExportTaskId(), sheetDIOList);
        //logger.info("异步导出工单列表出参：[{}]", JSON.toJSONString(responseDTO));
    }

    /**
     * 创建导出任务
     *
     * @param query
     * @param supportServiceItem
     */
    @StaffOperateRecord(staffId = "{{#query.staffId}}",
            event = EventEnum.WORK_ORDER_EXPORT,
            mapping = {
                    @RecordField(field = RecordFieldEnum.STAFF_IP, value = "{{#query.ip}}"),
                    @RecordField(field = RecordFieldEnum.PLAT, value = "{{#query.platWork}}")
            })
    @Override
    public void buildExportTask(OrderWorkQuery query, Boolean supportServiceItem) throws OmsBaseException {

        zsOrderWorkQueryBService.processWorkQuery(query);

        // 区分平台隐藏电话中间四位
//        String url;
//        Integer platWork = Optional.ofNullable(query.getPlatWork()).orElse(0);
//        switch (platWork) {
//            case GlobalConsts.PLAT_MARK_ZMN:
//                url = "/work/list/export/show/tel.action";
//                break;
//            case GlobalConsts.PLAT_MARK_YEYX:
//                url = "/ys/work/list/export/show/tel.action";
//                break;
//            case GlobalConsts.PLAT_MARK_SAAS:
//                url = "/saas/work/list/export/show/tel.action";
//                break;
//            case GlobalConsts.PLAT_MARK_CNHB:
//                url = "/cnhb/work/list/export/show/tel.action";
//                break;
//            default:
//                url = "/all/work/list/export/show/tel.action";
//                break;
//        }
//        boolean showTel = StaffAdminService.isPermitted(url);
        // query.setIsSensitiveTel(!showTel);
        query.setIsSensitiveTel(true);
        query.setIsSensitiveAddr(true);

        AddExportTaskDIO addExportTaskDIO = AddExportTaskDIO.builder()
                .exportType(EXPORT_TYPE)
                .exportName(ORDER_FILE_NAME)
                .fileType(EXPORT_FILE_TYPE)
                .staffId(query.getStaffId())
                .creater(query.getOperator())
                .build();
        ResponseDTO<Integer> responseDTO = exportModifyRemoteService.addExportTask(addExportTaskDIO);
        if (!responseDTO.isSuccess() || Objects.isNull(responseDTO.getData())) {
            throw new OmsBaseException("导出失败");
        }

        Integer exportTaskId = responseDTO.getData();
        query.setExportTaskId(exportTaskId);
        query.setSupportServiceItem(supportServiceItem);
        String json = JSON.toJSONString(query);
        String key = String.format("%s-%s", StringUtil.getRandomStringAndNumber3(26), exportTaskId);
        logger.debug("异步导出工单列表key：【{}】", key);
        zmnMQSender.send(MessageQueueTopicConstant.ZMN_TOPIC_OMS, MessageQueueTagConsts.ORDER_ASYNC_EXPORT, key, json);
    }

    /**
     * 业务线处理
     *
     * @param bizLine
     * @param bizLineMap
     * @return
     */
    private String processBizLine(Integer bizLine, HashMap<Integer, String> bizLineMap) {
        if (NumberUtil.isNullOrZero(bizLine)) {
            return "";
        }
        // 业务线处理
        String bizLineName = bizLineMap.get(bizLine);
        if (Objects.nonNull(bizLineName)) {
            return bizLineName;
        }

        ResponseDTO<Option<Integer>> nameVtRsp = productBusinessLineForeignListRemoteService.getOptionNameById(bizLine);
        Option<Integer> vtDTO = nameVtRsp.getData();
        if (Objects.nonNull(vtDTO)) {
            bizLineMap.put(bizLine, vtDTO.getLabel());
            return vtDTO.getLabel();
        }
        return "";
    }

    final static List<String> matchingRule = Arrays.asList("特殊收费", "产品销售");

    /**
     * 判断是否是一口价
     *
     * @param esOrderWork
     * @return
     */
    private boolean isFinalPrice(EsOrderWork esOrderWork) {
        boolean isFinalPrice = Objects.equals(true, esOrderWork.getIsFinalPrice())
                && Objects.equals(esOrderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE);
        return isFinalPrice;
    }
}